import type { CollecterParams } from "./types"
import { requestCount, requestPage, requestTypes } from "./request"

class Collecter {
  url: string = ""
  pg: number = 1
  pageCount: number = -1
  recordCount: number = -1
  params
  constructor(url: string, params: CollecterParams = {}) {
    this.url = url
    this.params = params
  }
  reset() {
    this.pg = 1
    this.pageCount = -1
    this.recordCount = -1
  }
  types = async () => await requestTypes(this.url)
  async nextPage() {
    if (this.pageCount === -1) {
      // 获取总页数
      const { pageCount, recordCount } = await requestCount(this.url, this.params)
      this.recordCount = recordCount
      this.pageCount = pageCount
      // this.pageCount = 3;
    }
    if (this.pg <= this.pageCount) {
      // 查询数据
      const videos = await requestPage(this.url, this.pg, this.params)

      this.pg++
      return videos
    }
    this.reset()
    return null
  }

  [Symbol.iterator]() {
    return this
  }

  async next() {
    const value = this.nextPage()
    return { done: value === null, value }
  }
}

export default Collecter
